require('dotenv').config();
const mongoose = require('mongoose');
const User = require('../src/models/user.model');
const Category = require('../src/models/category.model');
const Medicine = require('../src/models/medicine.model');
const Reminder = require('../src/models/reminder.model');

mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/medicine_db')
  .then(async () => {
    try {
      // 创建测试用户
      const user = await User.create({
        username: 'demo',
        password: '123456',
        nickname: '演示用户'
      });

      // 创建药品分类
      const categories = await Category.create([
        {
          name: '感冒药',
          description: '用于感冒症状的药品',
          userId: user._id
        },
        {
          name: '维生素',
          description: '补充维生素的药品',
          userId: user._id
        },
        {
          name: '消化药',
          description: '用于消化系统的药品',
          userId: user._id
        },
        {
          name: '止痛药',
          description: '用于缓解疼痛的药品',
          userId: user._id
        }
      ]);

      // 创建药品信息
      const medicines = await Medicine.create([
        {
          name: '布洛芬',
          imageUrl: '',
          efficacy: '缓解疼痛、退烧',
          specification: '0.2g*20片/盒',
          productionDate: new Date('2024-01-01'),
          expiryDate: new Date('2025-01-01'),
          remainingQuantity: 15,
          usage: '口服，一次1片，一日3次',
          precautions: ['不宜空腹服用', '服药期间注意休息'],
          categoryId: categories[3]._id,
          userId: user._id
        },
        {
          name: '维生素C片',
          imageUrl: '',
          efficacy: '补充维生素C，增强免疫力',
          specification: '0.1g*60片/瓶',
          productionDate: new Date('2024-02-01'),
          expiryDate: new Date('2025-02-01'),
          remainingQuantity: 45,
          usage: '口服，一次1片，一日1次',
          precautions: ['饭后服用'],
          categoryId: categories[1]._id,
          userId: user._id
        }
      ]);

      // 创建用药提醒
      const now = new Date();
      const reminder = await Reminder.create({
        userId: user._id,
        medicineId: medicines[0]._id,
        time: '08:00',
        repeat: 'daily',
        dosage: '1片',
        nextRemindTime: new Date(now.setHours(8, 0, 0, 0))
      });

      console.log('初始数据创建成功！');
    } catch (error) {
      console.error('创建初始数据失败:', error);
    } finally {
      mongoose.disconnect();
    }
  });